#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stddef.h>

// Configuration parameters
char g_url[80];
char g_arduino[80];
char g_ip[80];
int  g_id     = 9999;
int  g_delay  = 12; // Number of 10sec between data report
int  g_state  = 0;


//===============================
void delay(int t)
{
  t = t*1000; // convert to ms
  usleep(t);
}
//===============================
void processBrain()
//===============================
{
  FILE  *in;
  char  line[128];
  int i,com=0,par1=0,par2=0;
   
  strcpy(line,"empty");
  in = fopen("brain.msg","r");
  if(in == NULL)
    {
      printf("Unable to open brain.msg");
    }
  else
    {
      while (fgets(line,sizeof line,in) != NULL)
	  {
	    sscanf(line,"%d %d %d",&com,&par1,&par2);
	  }
	  // Check INBOX
      printf("INBOX: %s\n",line);

      if(g_state == 0)
      {
		  if(com == 1)g_state = 1; // Ack from server
	  }
      if(g_state == 1)
      {
          if(com == 2) // Change HeartBeat
          {
		    g_delay = par1;
	      }
	      if(com == 3) // Start BESSVX
          {
		    system("/var/www/bessvx &");
	      }
	      if(com == 4) // Start M2M
          {
		    system("/var/www/m2m &");
	      }
      }

    }
  fclose(in);	
  system("rm -f brain.msg");   
}
//===============================
void readConfig()
//===============================
{
  FILE  *in,*out;
  char  line[128];
  char  temps[12];

  in = fopen("brain.cfg","r");
  if(in == NULL)
    {
      printf("Create Brain config file\n");
      out = fopen("brain.cfg","w");
      fprintf(out,"URL:      m2m.simuino.com/brain.php\n");
      fprintf(out,"DELAY:    12\n"); // 12 sec
      fprintf(out,"IDENTITY: 9999\n"); 
      fclose(out);
      // Default values
      strcpy(g_url,   "m2m.simuino.com/brain.php");
      g_id           = 9999;
      g_delay        = 12; // Number of seconds
    }
  else
    {
      printf("Open config file\n");
      while (fgets(line,sizeof line,in) != NULL)
	  {
	    if(strstr(line,"URL:") != NULL)sscanf(line,"%s %s",temps,g_url);
	    if(strstr(line,"DELAY:") != NULL)sscanf(line,"%s %d",temps,&g_delay);
	    if(strstr(line,"IDENTITY:") != NULL)sscanf(line,"%s %d",temps,&g_id);
	  }
      fclose(in);
    }
}
//===============================
void readArduinoDevice()
//===============================
{
  FILE  *in,*out;
  char  line[128];
  char temps[12];
  
  strcpy(g_arduino,"no arduino found");
  system("ls /dev | grep ACM > brain.device");
  
  in = fopen("brain.device","r");
  if(in == NULL)
    {
      printf("No device information file\n");
    }
  else
    {
      //printf("Open device file\n");
      while (fgets(line,sizeof line,in) != NULL)
	{
	  if(strstr(line,"ttyACM") != NULL)sscanf(line,"%s",g_arduino);
	}
      fclose(in);
    }
}
//===============================
void readIpAddress()
//===============================
{
  FILE  *in;
  char  line[128];
  char  temps[12],*p;
  int   net = 0,netType=0;

  system("ifconfig > brain.ip");
  delay(1000);
  in = fopen("brain.ip","r");
  printf("Open ip file\n");
  strcpy(g_ip,"no ip found");
  while (fgets(line,sizeof line,in) != NULL)
  { 
	  if(strstr(line,"wlan") != NULL)
          {
             net = 1; //wlan
          }
	  if(strstr(line,"eth") != NULL)
          {
             net = 2; //eth
          }
	  if(strstr(line,"Loopback") != NULL)
          {
             net = 3; //lo
          }
	  if(strstr(line,"inet addr:") != NULL)
          {
             if(net != 3)
             {
               netType = net;
               sscanf(line,"%s %s",temps,g_ip);
             }
          }
      if(p=strstr(g_ip,"addr:")) {p=p+5;strcpy(g_ip,p);}
  }
  fclose(in);
  return;
}
//===============================
int main(int argc,char** argv)
//===============================
{   
  char res[120],com[120],sys[240];
    
  readConfig();
  readIpAddress();
  readArduinoDevice();

  printf("URL.........: %s\n",g_url);
  printf("Id..........: %d\n",g_id);
  printf("Delay.......: %d\n",g_delay);
  printf("IP..........: %s\n",g_ip);
  printf("Arduino.....: %s\n",g_arduino);
    
  //==================================================
    
  while(1)
    {
      //===========================
      // Start State Machine
      //===========================
	  if(g_state == 0) // Connect to Server
	  {
		  printf("SERVER CONNECTION\n");
		  sprintf(sys,"wget -q -O brain.msg \"http://%s?delay=%d&id=%d&msg=10&ip=%s\"",g_url,g_delay,g_id,g_ip);
          //printf("%s\n",sys);
          system(sys);
          processBrain();
	  }
	  if(g_state == 1) // IDLE state
	  {
          printf("IDLE HEARTBEAT %d\n",g_delay);
          sprintf(sys,"wget -q -O brain.msg \"http://%s?delay=%d&id=%d&msg=11\"",g_url,g_delay,g_id);
          //printf("%s\n",sys);
          system(sys);
          processBrain();
	  }
	  if(g_state == 2) // 
	  {
          printf("TBD\n");
	  }
      //===========================
      // End State Machine
      //===========================
      delay(10000); // Delay 10 seconds
    }
}
